import config from "../config"
import tool from "./tool"

let reconnectTime = 0
let reconnectTimer = null
let allowReconnect = true

let webSocketObject = null
let connected = false

let keepAliveTimer = null

const handleCreateConnection = () => {
    webSocketObject = new WebSocket(config.webSocketURL)
    console.log(`WS - 连接中...`)
    webSocketObject.onopen = () => {

        // 构造收发信息函数
        sendMessage = (key, value) => {
            if (!connected) throw 'WS未连接'
            webSocketObject.send(JSON.stringify({ key, value }))
        }
        webSocketObject.onmessage = (event) => {
            const message = JSON.parse(event.data)
            const { key, value } = message
            onMessageCallBacks.forEach((item) => {
                if (item.key === key) {
                    try {
                        item.callBack(value)
                    } catch (error) {

                    }
                }
            })
        }

        // 建立业务连接
        webSocketObject.send(JSON.stringify({ key: 'requestConnect', value: session_id }))
    }
    webSocketObject.onclose = async () => {
        console.log(`WS - 连接断开，正在重连...`)
        connected = false
        onCloseCallBacks.forEach((item) => {
            try {
                item()
            } catch (error) {

            }
        })
        clearTimeout(keepAliveTimer)
        // 重连
        if (allowReconnect) {
            await tool.wait(reconnectTime)
            reconnectTime = 3
            clearTimeout(reconnectTimer)
            reconnectTimer = setTimeout(() => {
                reconnectTime = 0
            }, 10000)
            handleCreateConnection()
        }
    }
}

// 发送信息函数
let sendMessage = undefined
// 接收信息函数
let onMessageCallBacks = []
let onMessage = (key, callBack) => {
    onMessageCallBacks.push({ key, callBack })
}
// 连接成功触发的业务逻辑
let onConnectedCallBacks = []
let onConnected = (callBack) => {
    onConnectedCallBacks.push(callBack)
}
onMessage('connected', (e) => {
    connected = true
    console.log(`WS - 连接成功`)

    // 事件
    onConnectedCallBacks.forEach((item) => {
        try {
            item(e)
        } catch (error) {

        }
    })
    setInterval(() => {
        try {
            sendMessage('keepAlive', {})
        } catch (error) {

        }
    }, 30000);
})
// 强制断开连接
let forceDisconnectCallBacks = []
let forceDisconnect = (callBack) => {
    forceDisconnectCallBacks.push(callBack)
}
onMessage('forceDisconnect', (e) => {
    allowReconnect = false
    console.log(`WS - 强制断开连接`)
    webSocketObject.close()
    forceDisconnectCallBacks.forEach((item) => {
        try {
            item(e)
        } catch (error) {

        }
    })
})

// 连接断开触发的业务逻辑
let onCloseCallBacks = []
let onClose = (callBack) => {
    onCloseCallBacks.push(callBack)
}

let session_id = undefined

export default {
    init(ssid) {
        session_id = ssid
        allowReconnect = true
        reconnectTime = 0
        clearTimeout(reconnectTimer)
        handleCreateConnection()
    },
    onConnected(callBack) {
        onConnected(callBack)
    },
    onMessage(key, callBack) {
        onMessage(key, callBack)
    },
    sendMessage(key, value) {
        sendMessage(key, value)
    },
    onClose(callBack) {
        onClose(callBack)
    },
    onForceDisconnect(callBack) {
        forceDisconnect(callBack)
    },
}